<?php

require_once WACT_ROOT . 'controller/controller.inc.php';
require_once WACT_ROOT . 'controller/form.inc.php';
require_once WACT_ROOT . 'validation/rules/match.inc.php';
require_once WACT_ROOT . 'validation/rules/member.inc.php';
require_once WACT_ROOT . 'validation/rules/pattern.inc.php';
require_once APP_ROOT . 'model/common/article.php';
require_once APP_ROOT . 'model/common/categories.php';
require_once APP_ROOT . 'model/common/session.php';
require_once APP_ROOT . 'model/common/form.php';
require_once APP_ROOT . 'model/common/user.php';
require_once APP_ROOT . 'model/common/date.php';
require_once APP_ROOT.'include/inc.config.php';


// article create/update form
class ArticleFormController extends FormController {

	var $admin_user = false;
	var $staff_user = false;
	var $view; // current view

	function setUserType($admin_user=false, $staff_user = false) {
		$this->admin_user = $admin_user;
        $this->staff_user = $staff_user;
	}

    function setView(&$view) {
    	$this->view = $view;
    }


	 function ArticleFormController() {
     	$this->addChild('create', new ButtonController(new Delegate($this, 'create'))); // create
        $this->addChild('save', new ButtonController(new Delegate($this, 'save'))); // save
        $this->addChild('delete', new ButtonController(new Delegate($this, 'delete'))); // delete

        $this->addChild('clean', new ButtonController(new Delegate($this, 'clean'))); // clean
        $this->addChild('articles', new ButtonController(new Delegate($this, 'back'))); // clean

        $this->setDefaultChild('clean');

        // validation
		$this->addRule(new Handle('RequiredRule', array('headline')));
        $this->addRule(new Handle('SizeRangeRule', array('headline', 50)));


        $this->registerOnLoadListener(new Delegate($this, 'load'));
        //$this->registerOnActivateListener(new Delegate($this, 'check'));

        $this->addView('delete', new Handle('RedirectView', array('/delete')));

	 }

	 function makeDateShow(&$responseModel) {
            //prepare show_date
            $day = $responseModel->get('show_day');
            $month = $responseModel->get('show_month');
            $year = $responseModel->get('show_year');

            if ($day>0 && $month>0 && $year>2000) {
            	$date_show = gmmktime(0,0,0, $month,$day,$year);
                //$tz =& new MyTimeZone();
            	//$date_show = $tz->timeLocal($date_show);
                $responseModel->set('date_show',gmdate("Y-m-d",$date_show));
            }
	 }

     function getCreationDateFromDateShow(&$responseModel) {
            //prepare show_date
            $day = $responseModel->get('show_day');
            $month = $responseModel->get('show_month');
            $year = $responseModel->get('show_year');

            $minutes = gmdate('i');
            $hours = gmdate('H');

            if ($day>0 && $month>0 && $year>2000) {
            	$date_show = gmmktime($hours,$minutes,0, $month,$day,$year);
            	$tz =& new MyTimeZone();
            	$date_show = $tz->timeLocal($date_show);
                $responseModel->set('date_added',gmdate("Y-m-d H:i",$date_show));
                return $date_show;
            }
	 }

     function checkCategories(&$source, &$request, &$responseModel) {
        // check that two categories are linked
            $category_id = $responseModel->get('category_id');
            $category2_id = $responseModel->get('category2_id');

            //print $category_id.'/'.$category2_id ;

            if (!$category_id && !$category2_id) {
                $responseModel->set('msg',"Error: At least one category must be selected!");
            	return false;
            }
            if ($category_id && $category2_id) {
            	$linked = CategoriesModel::AreCategoriesLinked($category_id, $category2_id);
            	//print 'result of check '.$linked;
            	if (!$linked) {
                    $responseModel->set('msg',"Error: The categories selected are not linked!");
                    //print $category_id.'/'.$category2_id." Not Linked!";
            		return false;
            	}
            }
            return true;
     }

     function create(&$source, &$request, &$responseModel) {
     	if ($responseModel->isValid()) {
            require_once WACT_ROOT.'/util/phpcompat/clone.php';

            if (!$this->checkCategories($source, $request, $responseModel) ) return 'this';


            //prepare show_date
            $this->makeDateShow($responseModel);

            //prepare author user
            $author_user_id = $responseModel->get('author_user_id');


            if (!$author_user_id && Session::isLogin()) {
            	$author_user_id = Session::getUserId();
            }
            if ($author_user_id) $responseModel->set('author_user_id',$author_user_id);

            $show_form = $responseModel->get('show_form');
            if (!$show_form) $responseModel->set('form_id',0);

            $creation = $responseModel->get('creation');

            if ( $creation ) {
            	//$date_show = $responseModel->get('date_show');
            	$this->getCreationDateFromDateShow($responseModel);
            } else {
            	$tz =& new MyTimeZone();
            	$responseModel->set('date_added', gmdate("Y-m-d H:i", $tz->timeNowLocal() ) );
            }
            // it does not allow for the 'description' field
            $desc = $responseModel->get('article_description');
            //print 'Description: '.$desc;
            if ($desc) $responseModel->set('description', $desc);

            $article_id = Article::insertArticle($responseModel);
            if ($article_id) {
            	$responseModel->set('article_id', $article_id);
                $lastRecord = clone_obj($responseModel);


                // Set up the model for adding the next record
                $responseModel->removeAll();
                $responseModel->set('LastRecord', $lastRecord);

                //print 'user-id='.$user_id." login = ".$login;


                return 'createOK';
            } else {
                return 'failure';
            }
        } else {
            //$responseModel->set('ShowPreview', TRUE);
        }
     }


	 function delete(&$source, &$request, &$responseModel) {
	 	return 'delete';
	 }


     function save(&$source, &$request, &$responseModel) {
        if ($responseModel->isValid()) {
        	$article_id = $request->getParameter('article_id');


        	if (!$this->checkCategories($source, $request, $responseModel) ) return 'this';

            //prepare show_date
            $this->makeDateShow($responseModel);

            $creation = $responseModel->get('creation');

            if ( $creation ) {
            	//$date_show = $responseModel->get('date_show');
            	$this->getCreationDateFromDateShow($responseModel);
            }

            //prepare author user
            $author_user_id = $responseModel->get('author_user_id');


            if (!$author_user_id && Session::isLogin()) {
            	$author_user_id = Session::getUserId();
            }
            if ($author_user_id) $responseModel->set('author_user_id',$author_user_id);

            //prepare admin user
            $admin_user_id = 0;
            if (Session::isLogin()) {
            	$admin_user_id = Session::getUserId();
            }
            if ($admin_user_id) $responseModel->set('admin_user_id',$admin_user_id);

            $show_form = $responseModel->get('show_form');
            if (!$show_form) $responseModel->set('form_id',0);

              // it does not allow for the 'description' field
            $desc = $responseModel->get('article_description');
            //print 'Description: '.$desc;
            if ($desc) $responseModel->set('description', $desc);

            if ($article_id && !$creation) Article::updateArticle($article_id, $responseModel);
            else if ($article_id) Article::updateArticleWithCreationDate($article_id, $responseModel);
            return 'saveOK';
        }
    }

    function clean(&$source, &$request, &$responseModel) {
        $responseModel->removeAll();
        $responseModel->set('supress_errors', 1);
    	return 'cleanOK';
    }

    function back(&$source, &$request, &$responseModel) {
        $responseModel->removeAll();
        $responseModel->set('supress_errors', 1);
    	return 'index';
    }

    // load show_date
    function loadDateShow(&$responseModel) {
       if ($responseModel->hasProperty('date_show')) {
       		$date_show = $responseModel->get('date_show');
       		//print $date_show;
       		//print strtotime($date_show);
       		$ts = strtotime($date_show);
            $tz =& new MyTimeZone();
            $ts = $tz->timeGMT($ts);
       		$day = (integer)gmdate('d',$ts);
       		$month = (integer)gmdate('m',$ts);
       		$year = (integer)gmdate('Y',$ts);
       		//print "   ".$day."/".$month."/".$year;
       		if ($day>0) $responseModel->set('show_day',$day);
            if ($month>0) $responseModel->set('show_month',$month);
            if ($year>0) $responseModel->set('show_year',$year);
       }

    }

     function load(&$source, &$request, &$responseModel) {
     	$article_id = $request->getParameter('article_id');
     	//print 'from load: user-id='.$user_id;
     	if ($article_id) {
        	$record =& Article::getRecord($article_id);
        	if (is_null($record)) {
            	return 'notfound';
        	}
            $responseModel->import($record->export());

            // prepare description
            $desc = $responseModel->get('description');
            $responseModel->set('article_description',$desc);

            // load show_date
            $this->loadDateShow($responseModel);
            $form_id = $responseModel->get('form_id');
            if ($form_id) $responseModel->set('show_form',1);

            //load width and height of the image
            $photo_url = $responseModel->get('small_picture');

            $mypos = strpos($photo_url, '/'); // if starts with /, append .
			if ( $mypos === 0) $photo_url = '.'.$photo_url;

            if ( stristr ($photo_url, "http://") )  $full_url = $photo_url;
            else  $full_url = HOST.'/'.$photo_url;
            //print  $full_url;
            //$full_url = rawurlencode( $full_url );
            $full_url = str_replace(' ','%20',$full_url); //REPLACE THE SPACES
            list($width, $height, $type, $attr) = @getimagesize($full_url);
            $responseModel->set('photo_width', $width);
            $responseModel->set('photo_height', $height);
            $responseModel->set('small_picture_url', $full_url);

            //load width and height of the image
            $photo_url = $responseModel->get('front_picture');
            $mypos = strpos($photo_url, '/'); // if starts with /, append .
			if ( $mypos === 0) $photo_url = '.'.$photo_url;

            if ( stristr ($photo_url, "http://") )  $full_url = $photo_url;
            else  $full_url = HOST.'/'.$photo_url;
            $full_url = str_replace(' ','%20',$full_url); //REPLACE THE SPACES
            //print  $full_url;
            list($width, $height, $type, $attr) = @getimagesize($full_url);
            $responseModel->set('photofront_width', $width);
            $responseModel->set('photofront_height', $height);
            $responseModel->set('front_picture_url', $full_url);



            // prepare the author
            $author_show = User::getFullUserName($responseModel);
            $responseModel->set('author_show', $author_show);

            // populate public_url
            $public_url = Article::getPublicURLByID($article_id);
            $responseModel->set('public_url', $public_url);


        }
     }

     //prepare the form view
     function prepare(&$source, &$request, &$responseModel, &$template) {
     	//print 'Prepare form...';
     	if ($this->admin_user) {
     		$responseModel->set('admin_user',1);
     	}
     	if ($this->staff_user) $responseModel->set('staff_user',1);
        $responseModel->set('host',HOST);

        // determine the current user
        if (Session::isLogin()) {
        	$user_id = Session::getUserId();
        	$isAuthor = User::isUserArticleWriter($user_id);
        	$isAdmin =  User::isUserAdmin($user_id);
        }

        if ($isAuthor) $responseModel->set('author_user',1);

     	//$template =& $view->Template;

        //populate months
        $show_month =& $template->getChild('show_month');

        $months_list =& SportDate::getMonthsList();
        $show_month->setChoices($months_list);

        //print_r($responseModel);


        //prepopulate date
        $tz =& new MyTimeZone();
        $now = $tz->timeNowLocal();
        $cur_month = (integer)date("m",$now);
        $cur_year = (integer)date("Y",$now);
        $cur_day = (integer)date("d",$now);

        if ( $cur_month==1 ) {
        	$prev_month = 12;
        	$prev_year = $cur_year-1;
        }  else {
           $prev_month = $cur_month - 1;
           $prev_year = $cur_year;
        }

        if ( $cur_month==12 ) {
        	$next_month = 1;
        	$next_year = $cur_year+1;
        }  else {
           $next_month = $cur_month + 1;
           $next_year = $cur_year;
        }

        $show_day =& $template->getChild('show_day');
        $day = $show_day->getValue();
        if (!$day) $show_day->setValue($cur_day);

        if ($show_month->getValue()<=0) $show_month->setSelection($cur_month);


        $show_year =& $template->getChild('show_year');
        $year = $show_year->getValue();
        if (!$year) $show_year->setValue($cur_year);

        //populate categories
        if ($isAuthor)  $categories1 =& CategoriesModel::getSportCategoriesForAuthor($user_id);
        else  $categories1 =& CategoriesModel::getSportCategories(false,false);
        //print_r($categories1);
        $categories2 =& CategoriesModel::getCommunityCategories(false,false);
        $category1 =& $template->getChild('category_id');
        $category2 =& $template->getChild('category2_id');
        $category1->setChoices($categories1);
        $category2->setChoices($categories2);

        //populate forms
        $forms_list =& FormModel::getFeedbackFormsForCombo();
        $forms =& $template->getChild('form_id');
        $forms->setChoices($forms_list);

        //populate permissions array
        //$user_id = 21;
        if ($user_id && $isAuthor) {
        	$permissions =& CategoriesModel::getSportCategoriesWithPermissions($user_id);
        	$template->setChildDataSource('permissions', $permissions);
        }

        // populate authors
        if ($isAdmin) {
        	$staffusers_list =& User::getStaffUsers();
        	$authors =& $template->getChild('author_user_id');
        	$authors->setChoices($staffusers_list);
        }


     }



}

?>